package com.bb;

import cn.hutool.http.HttpRequest;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.layout.font.FontProvider;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class HtmlToPdf {

    public static void main(String[] args) throws Exception {
        String html = HttpRequest.get("http://localhost:8080/genPdf/ABBB2020000").execute().body();

        FileOutputStream fileOutputStream = new FileOutputStream("D:/a.pdf");
        fileOutputStream.write(convert(html));
        fileOutputStream.close();
    }
    public static byte[] convert(String html) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ConverterProperties props = new ConverterProperties();
        FontProvider fp = new FontProvider(); // 提供解析用的字体
        fp.addStandardPdfFonts(); // 添加标准字体库、无中文
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//        fp.addDirectory(classLoader.getResource("fonts").getPath()); // 自定义字体路径、解决中文,可先用绝对路径测试。
        props.setFontProvider(fp);
        // props.setBaseUri(baseResource); // 设置html资源的相对路径
        HtmlConverter.convertToPdf(html, outputStream, props); // 无法灵活设置页边距等

        byte[] result = outputStream.toByteArray();
        outputStream.close();
        return result;
    }
}
